package com.basker.pisces.core.resource;

import java.io.IOException;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;

import com.basker.pisces.core.resource.annotation.ResouceLoader;
import com.basker.pisces.resource.StringResources;

@ResouceLoader(priority = Integer.MAX_VALUE, locationPatterns = {"classpath*:**/i18n/*.properties"})
public class StringResouceLoader implements IResourceLoader, InitializingBean {

    /**
     * 内置的文本资源
     */
    private Set<String> buildInResources;
    @Autowired
    private ResourcePatternResolver resolver;

    @Override
    public void afterPropertiesSet() throws Exception {
        loadBuildInResources();
    }

    @Override
    public void load(Resource[] resources) throws IOException {
        if (buildInResources != null) {
            resources = Stream.of(resources).filter(rs -> !buildInResources.contains(rs.toString()))
                    .toArray(s -> new Resource[s]);
        }

        StringResources.load(resources);
    }

    private void loadBuildInResources() throws IOException {
        Resource[] resources = resolver.getResources("classpath*:**/i18n/*pisces*.properties");

        if (resources.length > 0) {
            StringResources.load(resources);

            this.buildInResources = Stream.of(resources).map(s -> s.toString()).collect(Collectors.toSet());
        }
    }

}
